package com.example.appointment.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.example.appointment.R;
import com.example.appointment.adapter.ViewPagerAdapter;
import com.example.appointment.fragment.MyCollectionFragment;
import com.example.appointment.fragment.RecentWatchFragment;
import com.example.appointment.fragment.TeachFragment;
import com.example.appointment.fragment.UserCenterFragment;
import com.example.appointment.fragment.VideoCacheFragment;
import com.example.appointment.meta.CityVO;
import com.example.appointment.meta.EventBusVO;
import com.example.appointment.meta.MyCollectionSetVO;
import com.example.appointment.meta.ProvincesBean;
import com.example.appointment.util.AppJsonFileReader;
import com.example.appointment.util.Constant;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnPageChange;

/**
 * Created by Admin on 2016/8/31.
 */
public class HomePageActivity extends BaseActivity {
    @Bind(R.id.activity_home_page_delete_btn)
    Button deletebtn;//删除按钮


    @Bind(R.id.viewpager_main)
    ViewPager viewpagerMain;
    @Bind({R.id.tab_about_ball_friend, R.id.tab_talk_about_activities, R.id.tab_about_btn, R.id.tab_teaching, R.id.tab_message})
    TextView[] tabTexts;
//    @Bind({})

    private int[] tabdefaulticon = new int[]{R.mipmap.teach_default, R.mipmap.recent_default, R.mipmap.save_default, R.mipmap.cache_default, R.mipmap.me_default};//默认的按钮

//    @Bind({})

    private int[] tabpreicon = new int[]{R.mipmap.teach_pre, R.mipmap.recent_pre, R.mipmap.save_pre, R.mipmap.cache_pre, R.mipmap.me_pre};//点击的按钮

    private final static int fileName = R.raw.provincecitydistrict;

    @Bind(R.id.tab_bottom_layout)
    LinearLayout tabBottomLayout;
    protected List<String> dataList = new ArrayList<String>();
    protected ViewPagerAdapter adapter;

    private FragmentManager fragmentManager;
    private CityVO cityVO;
    //默认选择的界面
    protected int defaultIndex = 0;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setnotificationColore(R.color.color_343446);//設置导航栏顔色
        setContentView(R.layout.activity_home_page);
        ButterKnife.bind(this);

        ArrayList<ProvincesBean> provincesbean = (ArrayList<ProvincesBean>) DataSupport.findAll(ProvincesBean.class);
        if (provincesbean.size() == 0) {
            //判断是否需要重新读取
            initJSON();
        }

        fragmentManager = getSupportFragmentManager();

        initParams();
        initViewPager();
    }

    @OnClick({R.id.tab_about_ball_friend, R.id.tab_talk_about_activities, R.id.tab_about_btn, R.id.tab_teaching, R.id.tab_message})
    public void onClick(View view) {
        int index = 0;
        try {
//            setnotificationColore(R.color.colorAccent);
            index = Integer.valueOf(view.getTag().toString());
            if (index == 3) {
//如果是我的界面
//                更换主题、
                setTheme(R.style.ImageTranslucentTheme);
            } else {
                setTheme(R.style.AppTheme);
            }
        } catch (Exception e) {
            // handle exceptiononcreate
        }
        setSelected(index);
    }

//    @OnClick(R.id.tab_about_btn)
//    public void onClickAbout(View view) {
//        if (isAbout) {
//            fragmentManager.popBackStack();
//            isAbout = false;
//        } else {
//            addSouthFragment();
//            isAbout = true;
//        }
//    }

//    private void addSouthFragment() {
//        addFragment(R.anim.fragment_slide_in_from_bottom,
//                R.anim.fragment_slide_out_to_bottom,
//                R.anim.fragment_slide_in_from_bottom,
//                R.anim.fragment_slide_out_to_bottom, 0xa000ff00);
//    }

//    private void addFragment(int arg0, int arg1, int arg2, int arg3, int color) {
//        FragmentTransaction ft = fragmentManager.beginTransaction();
//        ft.setCustomAnimations(arg0, arg1, arg2, arg3);
//        MyCollectionFragment fragment = new MyCollectionFragment();
//        ft.add(R.id.rl_container, fragment);
//        ft.addToBackStack(null);
//        ft.commitAllowingStateLoss();
//    }[词典]	collection

    protected void initParams() {
        dataList = new ArrayList<String>();
        dataList.add(TeachFragment.class.getName());
        dataList.add(RecentWatchFragment.class.getName());
        dataList.add(MyCollectionFragment.class.getName());
        // 测试
        dataList.add(VideoCacheFragment.class.getName());
        dataList.add(UserCenterFragment.class.getName());
    }

    /**
     * 初始化页面布局
     */
    protected void initViewPager() {
        adapter = new ViewPagerAdapter(getSupportFragmentManager(), dataList);
        viewpagerMain.setAdapter(adapter);
        // 全放到内存中，listview
        viewpagerMain.setOffscreenPageLimit(4);
        // viewPager.setOnPageChangeListener(new TabOnpageChangeListener());
        // viewPager.setCurrentItem(defaultIndex);

        setSelected(defaultIndex);
    }

    public void setSelected(int position) {
        try {
            viewpagerMain.setCurrentItem(position, false);
            setSelectedStatus();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void setSelectedStatus() {
        // 设置选中状态
        for (int i = 0; i < tabTexts.length; i++) {
            if (i == viewpagerMain.getCurrentItem()) {
                // tabImgViews[i].setAlpha(hoverAlpha);
                tabTexts[i].setTextColor(0xff343446);
//                ColorStateList colorStateList = new ColorStateList();
//
//                tabTexts[i].setCompoundDrawableTintList(colorStateList);
                Drawable top = tabTexts[i].getCompoundDrawables()[1];
//                tabdefaulticon
//                        tabpreicon
                Drawable newtop = mContext.getResources().getDrawable(tabpreicon[i]);

                newtop.setBounds(0, 0, top.getBounds().height(), top.getBounds().width());//必须设置图片大小，否则不显示
                tabTexts[i].setCompoundDrawables(null, newtop, null, null);
//                setnotificationColore(R.color.colorAccent);
            } else {
                // tabImgViews[i].setAlpha(hoverAlpha / 2);
                tabTexts[i].setTextColor(0xffb6b6c0);
                Drawable top = tabTexts[i].getCompoundDrawables()[1];
                Drawable newtop = mContext.getResources().getDrawable(tabdefaulticon[i]);

                newtop.setBounds(0, 0, top.getBounds().height(), top.getBounds().width());//必须设置图片大小，否则不显示
                tabTexts[i].setCompoundDrawables(null, newtop, null, null);
            }
        }

    }

    @OnPageChange(R.id.viewpager_main)
    public void pageSelected(int position) {
        setSelected(position);
    }

    @OnPageChange(value = R.id.viewpager_main, callback = OnPageChange.Callback.PAGE_SCROLL_STATE_CHANGED)
    public void pageScrollStateChanged(int state) {
        if (state == ViewPager.SCROLL_STATE_IDLE) {
            setSelectedStatus();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    /**
     * 解析文件
     */
    private void initJSON() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                String jsonStr = AppJsonFileReader.getJson(HomePageActivity.this,
                        fileName);
                if (!TextUtils.isEmpty(jsonStr)) {
                    cityVO = JSON.parseObject(jsonStr, CityVO.class);
                    DataSupport.saveAll(cityVO.getCities());
                    DataSupport.saveAll(cityVO.getDistricts());
                    DataSupport.saveAll(cityVO.getProvinces());

                }
            }
        }).start();
    }


    /**
     * 与发布者在同一个线程
     */
    public void onEvent(MyCollectionSetVO itemvo) {
        deletebtn.setVisibility(View.VISIBLE);
        deletebtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除系列
                EventBusVO msg = new EventBusVO();
                msg.what = Constant.DELETE;

            }
        });

    }

    /**
     * 隐藏删除按钮
     *
     * @param itemvo
     */
    public void onEvent(ImageView itemvo) {
        deletebtn.setVisibility(View.GONE);

    }

}
